package org.caw.hbase.test.utils;

import java.io.File;
import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.LocalHBaseCluster;
import org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster;
import org.junit.Ignore;

/**
 * Start small local HBASE cluster with only one region server. UI of cluster is
 * disabled.
 * 
 * @author dino.keco
 * @version 0.1
 * @since 0.1
 */
@Ignore
public class HBaseCloud {

	private static final String ROOT = "test_cloud_data";
	private static final String ZK_PATH = ROOT + "/zk";
	private static final String HBASE = ROOT + "/hbase";

	static LocalHBaseCluster hbaseCluster;
	static MiniZooKeeperCluster zkCluster;

	public static void startup() throws IOException, InterruptedException {

		deleteFolder(new File(ROOT));
		zkCluster = new MiniZooKeeperCluster();
		zkCluster.setClientPort(2181);
		zkCluster.startup(new File(ZK_PATH));

		Thread.sleep(2000);

		Configuration conf = HBaseConfiguration.create();
		conf.set(HConstants.HBASE_DIR, HBASE);
		// disable web UI for cluster
		conf.set("hbase.regionserver.info.port", "-1");

		hbaseCluster = new LocalHBaseCluster(conf, 1);
		hbaseCluster.startup();

		Thread.sleep(5000);

	}

	public static void deleteFolder(File f) throws IOException {
		if (f.exists()) {
			if (f.isDirectory()) {
				for (File c : f.listFiles())
					deleteFolder(c);
			}
			if (!f.delete()) {
				throw new IOException("Failed to delete file: " + f);
			}
		}
	}

	public static void shutdown() {
		hbaseCluster.shutdown();

		try {
			Thread.sleep(5000);
			zkCluster.shutdown();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}